package com.neusoft.neuiotms.dcom.util;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.neusoft.bizcore.mom.bean.MessageBean;
import com.neusoft.bizcore.mom.messaging.ProducerService;
import com.neusoft.neuiotms.dcom.constants.DCOMConstants;
import com.neusoft.neuiotms.micro.notice.NoticeMicroService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SendingMessageDcom {
    @Autowired
    private NoticeMicroService systemNoticeMicroService;

    @Autowired
    private Environment environment;

    @Autowired
    private ProducerService producerService; //kafka 推送消息

    /**
     * @param notice 示例如下
     */
    //  {
    //  "system": {
    //          "noticeType": "maintenanceExpire",
    //          "users": ["wangsi"],
    //           "content": "您有资产维保即将到期 ,1类型下，共1台设备！",
    //          "businessInfo": "{\"s_asstTypeCodes\":\"1,\",\"s_maintenanceEndEnd\":1590303780137}"
    //        },
    // "mail": {
    //        "emailAddress": "wangsi@neusoft.com",
    //        "templateName": "noticeMail.ftl",
    //        "templateMsg": "{\"content\":\"您有资产维保即将到期 ,1类型下，共1台设备！\"}"
    //  },
    //   "appCode": "dcam",
    //   "type": ["email", "notice"],
    //   "title": "维保到期提醒"
    //
    //}
    public void SendMsgToNotice(final String notice) {
        final String kafka = this.environment.getProperty("spring.kafka.bootstrap-servers");
        SendingMessageDcom.log.info("kakfa地址： " + kafka);
        if (!StringUtils.isEmpty(kafka)) {
            final String topic = this.environment.getProperty("dcam.kafka.send-notice-topic");
            SendingMessageDcom.log.info("topic名称： " + topic);
            this.producerService.send(topic,
                    new MessageBean(notice, new Date()));
        } else {
            this.systemNoticeMicroService.createNotification(notice);
        }
        SendingMessageDcom.log.info("发送的消息内容是： " + notice);
    }

    public void SendImportResultToNotice(final String title, final String username, final String content) {
        final JSONObject obj = new JSONObject();
        final String[] type = {DCOMConstants.INFORM_TYPE_NOTICE, DCOMConstants.INFORM_TYPE_MAIL };
        obj.put("title", title);
        obj.put("type", type);
        obj.put("appCode", "dcam");

        final JSONObject sys = new JSONObject();
        sys.put("content", content);
        sys.put("noticeType", "basic");
        final String[] users = {username };
        sys.put("users", users);

        obj.put("system", sys);
        //        System.out.println(sys);
        this.SendMsgToNotice(obj.toString());
    }
}
